<template>
  <div class="">
    <el-form ref="mergeJoin" :model="mergeJoin" label-width="280px">
      <el-form-item label="步骤名称" prop="name">
        <el-input v-model="mergeJoin.name"></el-input>
      </el-form-item>
      <el-form-item label="第一个步骤" prop="step1">
        <el-select v-model="mergeJoin.step1" placeholder="请选择" style="width:100%" @focus="getStepsList">
          <el-option
            v-for="item in stepsList"
            :key="item.code"
            :label="item.name"
            :value="item.code">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="第二个步骤" prop="step2">
        <el-select v-model="mergeJoin.step2" placeholder="请选择" style="width:100%" @focus="getStepsList">
          <el-option
            v-for="item in stepsList"
            :key="item.code"
            :label="item.name"
            :value="item.code">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="连接类型" prop="join_type">
        <el-select v-model="mergeJoin.join_type" placeholder="请选择" style="width:100%">
          <el-option
            v-for="item in typeList"
            :key="item.code"
            :label="item.name"
            :value="item.code">
          </el-option>
        </el-select>
      </el-form-item>
      <el-row :gutter="20">
        <el-col :span="12">
          <span>第一个步骤的连接字段</span>
          <el-table :data="mergeJoin.keys_1" border style="margin-top:10px; width: 100%;" height="170">
            <el-table-column label="操作" align="center" fixed width="80" :resizable=false>
              <template slot-scope="scope">
                <div class="optionStyle">
                  <el-button
                    type="text"
                    @click="removeFirstStepFields(scope.$index)">移除
                  </el-button>
                </div>
              </template>
            </el-table-column>
            <el-table-column property="key" label="连接字段">
              <!--<template slot-scope="scope">-->
                <!--<el-input v-model="scope.row.key" size="mini"></el-input>-->
              <!--</template>-->
              <template slot-scope="scope">
                <el-select v-model="scope.row.key" filterable
                           allow-create placeholder="请选择">
                  <el-option
                    v-for="item in fieldOptions"
                    :key="item.name"
                    :label="item.name"
                    :value="item.name">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
          </el-table>
          <el-col :span="24">
            <el-row type="flex">
              <el-button class="el-table-add-row" @click="addFirstStepField()" icon="el-icon-plus">添加</el-button>
              <div style="width: 20px;"></div>
              <el-button class="el-table-add-row" @click="getFirstStepFields" icon="el-icon-thumb">获取连接字段</el-button>
            </el-row>
          </el-col>
        </el-col>
        <el-col :span="12">
          <span>第二个步骤的连接字段</span>
          <el-table :data="mergeJoin.keys_2" border style="margin-top:10px; width: 100%;" height="170">
            <el-table-column label="操作" align="center" fixed width="80" :resizable=false>
              <template slot-scope="scope">
                <div class="optionStyle">
                  <el-button
                    type="text"
                    @click="removeSecondStepFields(scope.$index)">移除
                  </el-button>
                </div>
              </template>
            </el-table-column>
            <el-table-column property="key" label="连接字段">
              <template slot-scope="scope">
                <el-select v-model="scope.row.key" filterable
                           allow-create placeholder="请选择">
                  <el-option
                    v-for="item in fieldOptions"
                    :key="item.name"
                    :label="item.name"
                    :value="item.name">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
          </el-table>
          <el-col :span="24">
            <el-row type="flex">
              <el-button class="el-table-add-row" @click="addSecondStepField()" icon="el-icon-plus">添加</el-button>
              <div style="width: 20px;"></div>
              <el-button class="el-table-add-row" @click="getSecondStepFields"  icon="el-icon-thumb">获取连接字段</el-button>
            </el-row>
          </el-col>
        </el-col>
      </el-row>
    </el-form>
    <div class="el-dialog__footer">
      <span class="dialog-footer">
          <el-button
            icon="el-icon-back"
            @click="cancel">取消
             </el-button>
             <el-button
               type="primary" icon="el-icon-check"
               @click="handleSaveData()">确定
           </el-button>
      </span>
    </div>
  </div>
</template>

<script>
  /* eslint-disable new-cap */
  import API from '../../../../../api/index'
  import mxgraph from '../../../../../graph/VueMxGraphLoader'
  const {
    mxUtils,
    mxCodec
  } = mxgraph
  export default {
    name: 'mergeJoin',
    props: {
      name: String
    },
    data () {
      return {
        fieldOptions: [],
        mergeJoin: {
          name: '',
          step1: [],
          step2: [],
          join_type: 'FULL OUTER',
          keys_1: [],
          keys_2: []
        },
        temp: {
          name: '',
          step1: [],
          step2: [],
          join_type: 'FULL OUTER',
          keys_1: [],
          keys_2: []
        },
        graph: null,
        tempMergeRows: null,
        stepsList: [],
        typeList: [{code: 'INNER', name: 'INNER'},
          {code: 'LEFT OUTER', name: 'LEFT OUTER'},
          {code: 'RIGHT OUTER', name: 'RIGHT OUTER'},
          {code: 'FULL OUTER', name: 'FULL OUTER'}]
      }
    },
    methods: {
      // 回显数据
      loadData (data) {
        if (data) {
          this.$forceUpdate()
          this.mergeJoin = Object.assign({}, data)
          this.tempMergeRows = JSON.parse(JSON.stringify(data))
        }
      },
      setGraph (val) {
        this.graph = val
        this.getStepsList()
      },
      // 重置表单数据
      resetFormData (stepname) {
        this.$forceUpdate()
        this.$refs['mergeJoin'].resetFields()
        this.mergeJoin = JSON.parse(JSON.stringify(this.temp))
        this.mergeJoin.name = stepname
      },
      saveTempPluginData (formData) {
        this.$emit('saveTempPluginData', formData)
      },
      getXml () {
        this.saveTempPluginData(this.mergeJoin)
        const graph = this.graph
        const enc = new mxCodec(mxUtils.createXmlDocument())
        const node = enc.encode(graph.getModel())
        const value = mxUtils.getPrettyXml(node)
        return value
      },
      async addSecondStepField () {
        let obj = {
          key: ''
        }
        this.mergeJoin.keys_2.push(obj)

        this.$nextTick(() => {
          let container = this.$el.querySelector('#field > .el-table__body-wrapper')
          container.scrollTop = container.scrollHeight
        })
        if (this.fieldOptions.length === 0) {
          const value = await this.getXml()
          API.trans.inputFields(value, {'stepName': this.mergeJoin.step2}).then(res => {
            if (res.data) {
              let tempFields = []
              const tempStreamField = Object.assign([], res.data)
              tempStreamField.forEach(element => {
                let obj = {}
                obj['name'] = element.name
                obj['comments'] = element.comments
                tempFields.push(obj)
              })
              this.$set(this, 'fieldOptions', tempFields)
            } else {
              this.fieldOptions = []
            }
          })
        }
      },
      async addFirstStepField () {
        let obj = {
          key: ''
        }
        this.mergeJoin.keys_1.push(obj)

        this.$nextTick(() => {
          let container = this.$el.querySelector('#field > .el-table__body-wrapper')
          container.scrollTop = container.scrollHeight
        })
        if (this.fieldOptions.length === 0) {
          const value = await this.getXml()
          API.trans.inputFields(value, {'stepName': this.mergeJoin.step1}).then(res => {
            if (res.data) {
              let tempFields = []
              const tempStreamField = Object.assign([], res.data)
              tempStreamField.forEach(element => {
                let obj = {}
                obj['name'] = element.name
                obj['comments'] = element.comments
                tempFields.push(obj)
              })
              this.$set(this, 'fieldOptions', tempFields)
            } else {
              this.fieldOptions = []
            }
          })
        }
      },
      // 获取第一个步骤的连接字段
      async getFirstStepFields () {
        const value = await this.getXml()
        this.mergeJoin.keys_1 = []
        if (this.mergeJoin.step1) {
          API.trans.inputFields(value, {'stepName': this.mergeJoin.step1}).then(res => {
            if (res.data) {
              for (var i = 0; i < res.data.length; i++) {
                this.mergeJoin.keys_1.push({ key: res.data[i].name })
              }
            } else {
              this.mergeJoin.keys_1 = []
            }
          })
        }
      },
      // 获取第二个步骤的连接字段
      async getSecondStepFields () {
        const value = await this.getXml()
        this.mergeJoin.keys_2 = []
        if (this.mergeJoin.step2) {
          API.trans.inputFields(value, {'stepName': this.mergeJoin.step2}).then(res => {
            if (res.data) {
              for (var i = 0; i < res.data.length; i++) {
                this.mergeJoin.keys_2.push({ key: res.data[i].name })
              }
            } else {
              this.mergeJoin.keys_2 = []
            }
          })
        }
      },
      // 移除第一个步骤的连接字段
      removeFirstStepFields (index) {
        this.mergeJoin.keys_1.splice(index, 1)
      },
      // 移除第二个步骤的连接字段
      removeSecondStepFields (index) {
        this.mergeJoin.keys_2.splice(index, 1)
      },
      // 获取第一、二个步骤的list
      async getStepsList () {
        if (this.stepsList.length === 0) {
          const value = await this.getXml()
          if (this.mergeJoin.name) {
            API.trans.previoussteps(value, {'stepName': this.mergeJoin.name}).then(res => {
              if (res.data) {
                this.stepsList = res.data
              } else {
                this.stepsList = []
              }
            })
          }
        }
      },
      // 保存表单数据
      handleSaveData () {
        if (this.mergeJoin.name) {
          this.$emit('savePluginData', this.mergeJoin)
        } else {
          this.$message({
            message: '步骤名称必填',
            type: 'warning'
          })
        }
      },
      // 重置数据
      cancel () {
        if (this.tempMergeRows) {
          this.saveTempPluginData(this.tempMergeRows)
        } else {
          let tempdata = JSON.parse(JSON.stringify(this.temp))
          tempdata['name'] = this.mergeJoin.name
          this.saveTempPluginData(tempdata)
        }
        this.$emit('cancel')
      }
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
  .el-form-item {
    margin-bottom: 10px !important;
  }
  .el-tabs /deep/ .el-tabs__content {
    padding: 15px !important;
  }
  .el-dialog__footer {
    margin-top: 49px;
  }
  .optionStyle button {
    margin: 0px
  }

</style>
